package 重温_Java并发基础.Synchronized案例;

import lombok.SneakyThrows;

/**
 * 不同加锁的方式
 *
 * @Author idea
 * @Date created in 9:28 下午 2020/8/17
 */
public class SynchronizedDiffWay {

    private static final Object obj = new Object();

    /**
     *
     */
    public static synchronized void staticMethod() {
        System.out.println("静态方法加锁");
    }

    /**
     * 锁住的是this对象
     */
    public synchronized void voidMethod() throws InterruptedException {
        System.out.println("voidMethod 非静态方法上边加锁");
//        Thread.sleep(1000);
        System.out.println("睡眠结束");
//        while (true) {
//
//        }
    }

    public synchronized void voidMethod2() {
        System.out.println("voidMethod2 当前对象被锁住了");
    }


    public static void main(String[] args) throws InterruptedException {

        /**
         * 论证使用synchronized针对非静态方法的处理场景是对this对象加锁
         */
        SynchronizedDiffWay s = new SynchronizedDiffWay();
        Thread t = new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                s.voidMethod2();
            }
        });
        t.start();


        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                s.voidMethod2();
            }
        });
        t2.start();

        t.join();
        t2.join();
        System.out.println("========= end =========");
    }

    public void blockMethod() {
        //保证被锁住的对象是唯一的
        synchronized (obj) {
            System.out.println("静态块加锁");
        }
    }
}
